package com.quartz;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import java.util.Date;


/**
 * QuartZ定时器使用
 * */
public class QuartZDemo01 {
    public static void main(String[] args) {
        //创建调度工厂类实例StdSchedulerFactory
        StdSchedulerFactory stdSchedulerFactory = new StdSchedulerFactory();
        try {
            //创建调度器实例Scheduler
            Scheduler scheduler = stdSchedulerFactory.getScheduler();
            //创建任务详情JobDetail
            JobDetail jobDetail = JobBuilder.newJob(MyJob.class)
                    .withIdentity("detail01", "group01")  //定义任务主键 组成唯一标识
                    .withDescription("this is a jobDetail")//描述
                    .usingJobData("name", "张三")//向具体执行的作业类传值方式一
                    .build();//构建任务
            //向具体执行的作业类传值方式二
            JobDataMap jobDataMap = jobDetail.getJobDataMap();
            jobDataMap.put("name", "张三");
            //创建触发器
            Trigger trigger = (Trigger) TriggerBuilder.newTrigger()
                    .withIdentity("trigger1", "group01")   //组成唯一标识
                    .startAt(new Date())             //开始时间
                    .withDescription("this is a trigger")
                    //简单触发器
                    .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                            //每隔两秒重复执行3次
                            .withIntervalInSeconds(2).withRepeatCount(3))
                    //表达式调度器（在线生成定时任务表达式：http://cron.qqe2.com/）
                    //每5秒执行一次作业类逻辑代码
                    //.withSchedule(CronScheduleBuilder.cronSchedule("0/5 * * * * ? "))
                    .build();
            //注入作业类以及触发器到调度器中
            scheduler.scheduleJob(jobDetail, trigger);
            //启动调度器
            scheduler.start();

        } catch (SchedulerException e) {
            e.printStackTrace();
        }

    }



    /**
     * 自定义任务
     * 注意，如果是内部类，不能定义为private类型
     * */
    public static class MyJob implements Job {

        @Override
        public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
            Object name = jobExecutionContext.getJobDetail().getJobDataMap().get("name");
            System.out.println("test executing task "+name);
        }
    }
}
